# -*- coding: utf-8 -*-
"""
Module Description:
Date: 2015/12/28
Author:Bai Jin Ping
"""
import collections


def dict_sub(d1, d2):
    """
    数值字典减法
    同key的val相减，若字典1有，字典2没有的key，得原值；反之不处理
    :param d1:字典1
    :param d2: 字典2
    :return:
    """
    result_dict = {}
    for k, v in d1.iteritems():
        if k not in d2:
            result_dict[k] = v
        else:
            v = v - d2[k]
            if v > 0:
                result_dict[k] = v
    return result_dict


def dict_merge(dct, merge_dct):
    """
    https://gist.github.com/angstwad/bf22d1822c38a92ec0a9

    :param dct: dict onto which the merge is executed
    :param merge_dct: dct merged into dct
    :return: None
    """
    if not merge_dct:
        return dct

    for k, v in merge_dct.iteritems():
        if (k in dct and isinstance(dct[k], dict)
                and isinstance(merge_dct[k], collections.Mapping)):
            dict_merge(dct[k], merge_dct[k])
        else:
            dct[k] = merge_dct[k]
    return dct


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i + n]


def tree():
    """
    构造一颗字典树
    """
    return collections.defaultdict(tree)


if __name__ == '__main__':
    d1 = {
        1: 1,
        2: 2
    }
    d2 = {
        2: 2,
        3: 3
    }
    print dict_sub(d1, d2)
    pass
